#include "rolenetserver.h"

RoleNetServer::RoleNetServer(QObject *parent) :
    QTcpServer(parent)
{
}

void RoleNetServer::StartServer()
{
    if (!this->listen(QHostAddress::Any, 1338)) // 1337 is reserved for radio request server c:
    {
        qDebug() << "[!] Serwer nie wystartowal!";
    }else{
        qDebug() << "[*] Serwer wystartowal!";
    }
}

void RoleNetServer::incomingConnection(int handle)
{
    qDebug() << "[*] Nowe polaczenie: " << handle;
    ConnectionThread *thread = new ConnectionThread(handle, this); // Allocate new thread
    connect(this, SIGNAL(writing(QByteArray)), thread, SLOT(writeToSocket(QByteArray))); // This is tricky, I'll leave it for future.
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // It's necessary to delete later, in case some resources are still allocated while thread ended working
    connect(thread, SIGNAL(relay(QByteArray)), this, SLOT(receiveData(QByteArray)));
    thread->start();
    QList<ConnectionThread *> thrlist = findChildren<ConnectionThread *>();
    for (int i = 0; i < thrlist.size(); i++) {
        qDebug() << "Polaczony klient: " << i;
        //thread->writeToSocket("NewCon");
        this->WriteToAll("NewCon");
    }

}

void RoleNetServer::WriteToAll(QByteArray data)
{
    //emit writing(data); // emit signal to send data for every connected client - left 4 future
    // TODO - use QList to pass data through every active thread
    emit writing("test");
}

void RoleNetServer::receiveData(QByteArray data)
{
    // Get the data and relay for every connected client
    qDebug() << data; 
    WriteToAll(data);
}
